<?php

namespace App\HttpController\Pay;

use EasySwoole\Core\Http\AbstractInterface\Controller;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;
use Exception;
use EasySwoole\Core\Http\Message\Status;

class WxPaySdk extends Controller {
	protected $config = [ 
			'appid' => 'wxb3fxxxxxxxxxxx', // APP APPID
			'app_id' => 'wxb3fxxxxxxxxxxx', // 公众号 APPID
			'miniapp_id' => 'wxb3fxxxxxxxxxxx', // 小程序 APPID
			'mch_id' => '14577xxxx',
			'key' => 'mF2suE9sU6Mk1Cxxxxxxxxxxx',
			'notify_url' => 'http://chat.7b620.cn/Pay/WxPaySdk/notify.php',
			'cert_client' => './cert/apiclient_cert.pem', // optional，退款等情况时用到
			'cert_key' => './cert/apiclient_key.pem', // optional，退款等情况时用到
			'log' => [  // optional
					'file' => './logs/wechat.log',
					'level' => 'debug' 
			],
			'mode' => 'dev'  // optional, dev/hk;当为 `hk` 时，为香港 gateway。
	];
	private $wxpay = null;
	protected function onRequest($action): ?bool {
		$this->wxpay = Pay::wechat ( $this->config );
		return true;
	}
	protected function actionNotFound($action): void {
		$this->response ()->withStatus ( Status::CODE_NOT_FOUND );
	}
	public function index() {
		$order = [ 
				'out_trade_no' => time (),
				'total_fee' => '1', // **单位：分**
				'body' => 'test body - 测试',
				'openid' => 'onkVf1FjWS5SBIixxxxxxx' 
		];
		
		$pay = $this->wxpay->mp ( $order );
		
		// $pay->appId
		// $pay->timeStamp
		// $pay->nonceStr
		// $pay->package
		// $pay->signType
	}
	public function notify() {
		try {
			$data = $this->wxpay->verify (); // 是的，验签就这么简单！
			
			Log::debug ( 'Wechat notify', $data->all () );
		} catch ( Exception $e ) {
			$e->getMessage ();
		}
		
		$success = $this->wxpay->success ()->send (); // laravel 框架中请直接 `return $pay->success()`
		$this->response ()->write ( $success );
	}
}
